package com.sdyeda.dtu.fx;

import java.util.ArrayList;
import java.util.List;

import com.sdyeda.dtu.net.DtuInfo;
import com.sdyeda.dtu.net.IotInfo;
import com.sdyeda.dtu.net.Server;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableView;

public class MainWindowController {

	@FXML
	private TreeTableView<DtuInfo> dtulist;

	@FXML
	private TableView<IotInfo> iotlist;

	@FXML
	public void initialize() {
		dtulist.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
			List<IotInfo> list = new ArrayList<>();
			//System.out.println(newValue);
			if(newValue == null)	//刷新树导致空值
				return;

			if (newValue.getValue().getId().equals("所有DTU")) {
				Server.getDtuclients().forEach(item -> {
					item.getIots().forEach(iot -> list.add(iot));
				});
			} else {
				Server.getDtuclients().forEach(item -> {
					if (item.equals(newValue.getValue())) {
						item.getIots().forEach(iot -> list.add(iot));
					}
				});
			}
			Platform.runLater(() -> {
				iotlist.setItems(FXCollections.observableArrayList(list));
				iotlist.refresh();
			});
		});

	}

	@FXML
	public void refush() {
		// TreeTableColumn<DtuInfo,String> root = new TreeTableColumn<>("所有DTU");
		TreeItem<DtuInfo> root = new TreeItem<>(new DtuInfo("所有DTU", "", 0));

		Server.getDtuclients().forEach(item -> {
			root.getChildren().add(new TreeItem<DtuInfo>(item));
		});

		Platform.runLater(() -> {
			root.setExpanded(true);

			dtulist.setRoot(root);
			dtulist.refresh();
		});

	}
}
